package com.congwulin.wechat.controller;

import com.congwulin.wechat.entity.user.User;
import com.congwulin.wechat.service.UserService;
import com.congwulin.wechat.util.ReturnData;
import com.congwulin.wechat.util.StatusCode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;

@Controller
@RequestMapping(value = "/login")
public class LoginController {

    @Autowired
    private UserService service;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @RequestMapping(value = "/getLoginSession",method = RequestMethod.GET)
    public @ResponseBody ReturnData login(HttpServletRequest request, String account, String password){
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        User loginUser = service.getUserInfo(user);
        if(loginUser!=null){
            HttpSession session = request.getSession();
            session.setAttribute("loginUserId", loginUser.getId());
            redisTemplate.opsForValue().set("loginUser:" + loginUser.getId(), session.getId());

            return new ReturnData(StatusCode.SUCCESS, loginUser, "登录成功！");
        }else{
            return new ReturnData(StatusCode.FAIL, null, "账号密码错误，无法登录！");
        }
    }

    @RequestMapping(value = "/getUserInfo",method = RequestMethod.GET)
    public @ResponseBody ReturnData get(String account, String password)
    {
        User user = new User();
        user.setAccount(account);
        user.setPassword(password);
        User loginUser = service.getUserInfo(user);
        if (loginUser != null)
        {
            return new ReturnData(StatusCode.SUCCESS, loginUser, "查询成功！");
        }
        else
        {
            return new ReturnData(StatusCode.FAIL, null, "账号密码错误，没有对应的用户！");
        }
    }

    @RequestMapping(value = "saveUser", method = RequestMethod.POST)
    public @ResponseBody
    List<User> saveProduct(@RequestBody List<User> users){
        return service.saveUser(users);
    }
}
